package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.common.excepcion.SUBException;
import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.UsuarioSubprogramaService;
import co.gov.medellin.ssti.sub.model.vo.UsuarioSubprogramaVO;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;

public class AllocationPermissionReportAction extends Action {
	@Autowired
	UsuarioSubprogramaService usuarioSubprogramaServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	@SuppressWarnings("unchecked")
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		HttpSession session = request.getSession();

		List<String> lUsuarioSelect = new LinkedList<String>();
		// List lSubprogSelect = new LinkedList();
		List<UsuarioSubprogramaVO> Errores = new LinkedList<UsuarioSubprogramaVO>();

		// Proceso para la auditoria
		UserVO user = (UserVO) request.getSession().getAttribute("userInfo");
		String terminalAddress = request.getRemoteAddr();
		String strTerminal = ("WEB=" + terminalAddress);
		Calendar c = Calendar.getInstance();
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		// Fin del proceso

		String strTamanoSubprog = (String) session.getAttribute("TamanoSubpro");
		int iTamanoSubprog = Integer.parseInt(strTamanoSubprog.trim());
		lUsuarioSelect = (List<String>) session.getAttribute("ListadeUsuarios");

		for (int i = 0; i < lUsuarioSelect.size(); i++) {
			for (int j = 0; j < iTamanoSubprog; j++) {
				String strNombre = "subprograma" + j;
				String strCodeSubprog = request.getParameter(strNombre);
				if ((Object) strCodeSubprog != null) {
					try {
						// Proceso para identificar si el usuario ya tiene
						// permisos el beneficio
						List<UsuarioSubprogramaVO> lVerificar = new LinkedList<UsuarioSubprogramaVO>();
						lVerificar = usuarioSubprogramaServiceImpl
								.findPermisosUsuarios(new Long(
										((String) lUsuarioSelect.get(i))),
										new Long(strCodeSubprog));
						// Fin del proceso
						if (lVerificar.size() > 0) {
							Errores.addAll(lVerificar);
						} else {
							String strArr[] = { strCodeSubprog,
									((String) lUsuarioSelect.get(i)),
									user.getName(),
									dateFormat.format(c.getTime()),
									strTerminal, user.getName(),
									dateFormat.format(c.getTime()), strTerminal };
							int iInsertCorrecto = usuarioSubprogramaServiceImpl
									.insertPermisosReportes(strArr);
						}

					} catch (DAOException e) {
						SUBException.logDebugError("", e);
					}
				}
			}
		}
		if (Errores.size() > 0) {
			request.setAttribute("msgerror",
					"Los siguientes usuarios ya tienen permisos sobre los beneficios");
			request.setAttribute("lErrores", Errores);
		} else
			request.setAttribute("msgc",
					"Los permisos se otorgaron correctamente");
		return mapping.findForward("success");
	}
}